package com.javabi.common.lang;

/**
 * A class for displaying bytes in a human-readable format.
 */
public class ByteSize {

	/** The size. */
	private final long size;
	/** The main divisor (should be 1000 or 1024). */
	private int divisor = 1024;

	/**
	 * Creates a new byte size.
	 * @param size the size.
	 */
	public ByteSize(long size) {
		this.size = size;
	}

	/**
	 * Creates a new byte size.
	 * @param bytes the bytes.
	 */
	public ByteSize(byte[] bytes) {
		this(bytes.length);
	}

	/**
	 * Returns the size.
	 * @return the size.
	 */
	public long getSize() {
		return size;
	}

	/**
	 * Returns the divisor.
	 * @return the divisor.
	 */
	public int getDivisor() {
		return divisor;
	}

	/**
	 * Set the divisor, usually 1000 or 1024.
	 * @param divisor the divisor indicating how bytes are measured.
	 */
	public void setDivisor(int divisor) {
		if (divisor < 1) {
			throw new IllegalArgumentException("divisor=" + divisor);
		}
		this.divisor = divisor;
	}

	@Override
	public String toString() {

		// Bytes
		long bytes = size % divisor;
		long kb = size / divisor;
		if (kb <= 0) {
			return bytes + " bytes";
		}

		// Kilobytes
		long mb = kb / divisor;
		if (mb <= 0) {
			bytes /= 100;
			return kb + "." + bytes + " KB";
		}

		// Megabytes
		long gb = mb / divisor;
		if (gb <= 0) {
			kb %= divisor;
			kb /= 100;
			return mb + "." + kb + " MB";
		}

		// Gigabytes
		mb %= divisor;
		mb /= 100;
		return gb + "." + mb + " GB";
	}

}
